<template>
	<view class="page-container">
		<!-- 固定在顶部的导航栏-->
		<view class="fixed-nav-bar" :class="{ show: isNavFixed }">
			<view class="fixed-user-info">
				<image class="fixed-avatar" :src="getFullAvatarUrl(userInfo.avatar) || defaultAvatar" mode="aspectFill">
				</image>
				<text class="fixed-username">{{userInfo.name || '未登录'}}</text>
			</view>

			<view class="fixed-actions">
				<view class="fixed-action" @click="navTo('/pages/user/wallet/wallet')">
					<image class="fixed-action-icon" src="/static/center/我的钱包.png" mode="widthFix"></image>
					<text class="fixed-action-text">钱包</text>
				</view>
				<view class="fixed-action" @click="navTo('/pages/user/service/service')">
					<image class="fixed-action-icon" src="/static/center/个人客服.png" mode="widthFix"></image>
					<text class="fixed-action-text">客服</text>
				</view>
			</view>
		</view>
		<!-- 用户信息卡片 -->
		<view class="card user-card mb-md">
			<image class="bg" src="/static/center/background.webp"></image>
			<view class="user-info-box">
				<view class="portrait hover-press" @click="uploadAvatar">
					<image mode="aspectFill" :src="getFullAvatarUrl(userInfo.avatar) || defaultAvatar"></image>
				</view>
				<view class="username">
					<view @click="editNickname">{{userInfo.name}}</view>
					<view class="phone">{{safeUserData.phone}}</view>
					<view class="balance">余额: {{userInfo.balance || 0}}元</view>
				</view>
			</view>
		</view>

		<!-- 核心功能卡片 -->
		<view class="card mb-md">
			<view class="grid grid-3">
				<view class="grid-item hover-scale" @click="navTo('/pages/user/wallet/wallet')">
					<image class="grid-icon" src="/static/center/我的钱包.png" mode="widthFix"></image>
					<text class="grid-text">钱包</text>
				</view>
				<view class="grid-item hover-scale" @click="navTo('/pages/user/service/service')">
					<image class="grid-icon" src="/static/center/个人客服.png" mode="widthFix"></image>
					<text class="grid-text">客服</text>
				</view>
				<view class="grid-item hover-scale" @click="navTo('/pages/user/refund/refund')">
					<image class="grid-icon" src="/static/center/退款.png" mode="widthFix"></image>
					<text class="grid-text">退款</text>
				</view>


			</view>
		</view>

		<!-- 订单相关卡片 -->
		<view class="card mb-md">
			<view class="order-section">
				<view class="order-item hover-scale" @click="navTo('/pages/talking/talking')">
					<image class="order-icon" src="/static/center/评价.png" mode="widthFix"></image>
					<text>评价</text>
				</view>
				<view class="order-item hover-scale" @click="navTo('/pages/user/collect')">
					<image class="order-icon" src="/static/center/收藏.png" mode="widthFix"></image>
					<text>收藏</text>
				</view>
				<view class="order-item hover-scale" @click="navTo('/pages/user/address/list')">
					<image class="order-icon" src="/static/center/收货地址.png" mode="widthFix"></image>
					<text>收货地址</text>
				</view>

			</view>
		</view>

		<!-- 系统功能卡片 -->
		<view class="card">
			<view class="history-section icon">
				<list-cell icon="icon-round_favor_fill" iconColor="#e07472" title="浏览记录"
					@eventClick="navTo('/pages/user/history')"></list-cell>
				<list-cell icon="icon-settings" iconColor="#e07472" title="关于" border=""
					@eventClick="navTo('/pages/base/about')"></list-cell>
				<list-cell icon="icon-exit" iconColor="#e07472" title="退出登录" border=""
					@eventClick="handleLogout"></list-cell>
				<list-cell icon="icon-switch" iconColor="#5eba8f" title="切换账号" border=""
					@eventClick="navTo('/pages/user/account/account')"></list-cell>
				<list-cell icon="icon-switch" iconColor="#5eba8f" title="优惠券" border=""
					@eventClick="navTo('/pages/user/center/envelope')"></list-cell>
				<list-cell icon="icon-switch" iconColor="#5eba8f" title="扫码登录" border=""
					@eventClick="navTo('/pages/user/scan-login/index')"></list-cell>
			</view>

		</view>

		<!-- 底部滑入弹窗 -->
		<uni-popup ref="nicknamePopup" type="bottom" :animation="true" :mask="true" :mask-click="false"
			@change="onPopupChange">
			<view class="nickname-popup">
				<view class="drag-indicator"></view>

				<view class="popup-header">
					<text class="popup-title">修改昵称</text>
					<text class="popup-close hover-press" @click="closeNickname">×</text>
				</view>

				<view class="popup-content">
					<input class="nickname-input" v-model="newNickname" :placeholder="userInfo.name || '请输入新昵称'"
						maxlength="16" placeholder-style="color:#ccc" @input="handleInput" />

					<view class="input-hint">
						<text>{{newNickname.length}}/16</text>
						<text v-if="newNickname.length < 2 && newNickname.length > 0"
							class="warning">昵称长度不能少于2个字符</text>
					</view>

					<view class="policy-container">
						<label class="policy-checkbox hover-press" @click="toggleAgree">
							<checkbox :checked="agreePolicy" color="#5eba8f"
								style="transform: scale(0.8); vertical-align: middle;" />
							<text class="policy-label">我已阅读并同意以下规定</text>
						</label>

						<view class="policy-content">
							<text class="policy-title">符合法律法规要求：</text>
							<text class="policy-text">
								根据国家互联网信息办公室发布的《互联网用户账号名称信息管理规定》，互联网用户账号使用者在注册、使用账号名称信息中应当遵循相关原则，账号名称信息不得模仿、类似党政军机关、新闻媒体、企事业单位等组织机构的名称、标识等。
							</text>
						</view>
					</view>
				</view>

				<button class="btn btn--primary btn--block submit-btn" :class="{ 'submit-btn--disabled': !canSubmit }"
					@click="submitNickname" :disabled="!canSubmit">
					确认修改
				</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import hxNavbar from "@/components/hx-navbar/hx-navbar.vue"
	import AccountSwitch from '@/components/AccountSwitch.vue'
	import listCell from '@/components/mix-list-cell';
	import apiConfig from '@/config/api.config'
	import {
		config
	} from '@/utils/request';
	import {
		mapState
	} from 'vuex';

	let startY = 0,
		moveY = 0,
		pageAtTop = true;

	export default {
		components: {
			listCell,
			hxNavbar,
			AccountSwitch
		},
		data() {
			return {
				isNavFixed: false,
				scrollTop: 0,
				userCardTop: 0,
				isH5: process.env.UNI_PLATFORM === 'h5',
				nickName: "未设置昵称",
				defaultAvatar: '/static/img/1.png',
				userInfo: {},
				admin_judge: false,
				a: 0,
				pageTitle: "我的",
				coverTransform: 'translateY(0px)',
				coverTransition: '0s',
				moving: false,
				defaultFace: '/static/img/user/missing-face.png',
				userSettingUrl: '/pages/user/setting/setting',
				memberInfo: {
					face: '',
					nickname: "",
				},
				baseURL: config ? config.baseURL : (process.env.VUE_APP_PLATFORM === 'h5' ? '/api' :
					'http://localhost:8080'),
				newNickname: '',
				popupShow: false,
				agreePolicy: false,
			}
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			// 当滚动距离超过用户卡片高度时，固定导航栏
			this.isNavFixed = this.scrollTop > this.userCardTop;
		},
		onLoad() {
			this.loadUserInfo();
		},
		onShow() {
			this.loadUserInfo();
		},
		onReady() {
			// 获取用户卡片的位置信息
			this.$nextTick(() => {
				const query = uni.createSelectorQuery().in(this);
				query.select('#user-card').boundingClientRect(rect => {
					if (rect) {
						this.userCardTop = rect.top;
					}
				}).exec();
			});
		},
		computed: {
			...mapState('user', ['hasLogin', 'userData']),
			safeUserData() {
				return this.userData || {
					phone: '',
					username: '',
					avatar: ''
				}
			},
			canSubmit() {
				const validNickname = this.newNickname.trim().length >= 2 && this.newNickname.trim().length <= 16;
				return validNickname && this.agreePolicy;
			}
		},
		methods: {
			checkDefaultAvatar() {
				uni.getFileSystemManager().access({
					filePath: this.defaultAvatar,
					success: () => {
						console.log('默认头像存在');
					},
					fail: () => {
						console.warn('默认头像不存在，使用备用头像');
						this.defaultAvatar = 'http://127.0.0.1:9300/statics/2025/default.jpg';
					}
				});
			},

			navTo(url) {
				uni.navigateTo({
					url,
					animationType: 'slide-in-right',
					animationDuration: 300
				});
			},

			goToAddressList() {
				this.navTo('/pages/user/address/list');
			},

			handleLogout() {
				this.$store.dispatch('user/logout').then(() => {
					uni.showToast({
						title: '已退出登录',
						icon: 'success'
					});
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/login'
						});
					}, 1500);
				});
			},

			coverTouchstart(e) {
				if (pageAtTop === false) return;
				this.coverTransition = 'transform .1s linear';
				startY = e.touches[0].clientY;
			},

			coverTouchmove(e) {
				moveY = e.touches[0].clientY;
				let moveDistance = moveY - startY;
				if (moveDistance < 0) {
					this.moving = false;
					return;
				}
				this.moving = true;
				if (moveDistance >= 80 && moveDistance < 100) {
					moveDistance = 80;
				}
				if (moveDistance > 0 && moveDistance <= 80) {
					this.coverTransform = `translateY(${moveDistance}px)`;
				}
			},

			coverTouchend() {
				if (this.moving === false) return;
				this.moving = false;
				this.coverTransition = 'transform 0.3s cubic-bezier(.21,1.93,.53,.64)';
				this.coverTransform = 'translateY(0px)';
			},

			async loadUserInfo() {
				const userId = this.$store.getters['user/userId'];
				if (!userId || isNaN(Number(userId))) {
					console.error('用户ID无效或未登录');
					return;
				}
				const userIdNum = Number(userId);

				try {
					const res = await this.$api.userApi.getUserInfo(userIdNum);
					if (res.code === 200) {
						this.userInfo = res.data;
					}
				} catch (e) {
					console.error('获取用户信息失败', e);
					uni.showToast({
						title: '获取用户信息失败',
						icon: 'none'
					});
				}
			},

			uploadAvatar() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];
						const userId = this.$store.getters['user/userId'];

						if (!userId) {
							uni.showToast({
								title: '请先登录',
								icon: 'none'
							});
							return;
						}

						// 构建上传URL
						const isH5 = process.env.UNI_PLATFORM === 'h5';
						const fullUrl = isH5 ?
							`${apiConfig.h5.proxy}${apiConfig.uploadPath}` :
							`${apiConfig.app}${apiConfig.uploadPath}`;

						const headers = {
							...(this.$store.getters['user/isLogin'] ? {
								'Authorization': `Bearer ${this.$store.state.user.token}`
							} : {})
						};

						uni.uploadFile({
							url: fullUrl,
							filePath: tempFilePath,
							name: 'file',
							formData: {
								'id': userId
							},
							header: headers,
							success: (uploadRes) => {
								try {
									const result = JSON.parse(uploadRes.data);
									if (result.code === 200 && result.data.url) {
										this.userInfo.avatar = result.data.url;
										this.$store.commit('user/SET_TOKEN', {
											token: this.$store.state.user.token,
											userData: {
												...this.$store.state.user.userData,
												avatar: result.data.url
											}
										});
										uni.showToast({
											title: '头像上传成功',
											icon: 'success'
										});
									} else {
										uni.showToast({
											title: '上传失败: ' + (result.msg || '未知错误'),
											icon: 'none'
										});
									}
								} catch (e) {
									console.error('解析上传结果失败', e);
									uni.showToast({
										title: '上传失败，服务器响应格式错误',
										icon: 'none'
									});
								}
							},
							fail: (err) => {
								console.error('上传请求失败', err);
								uni.showToast({
									title: '上传失败，请检查后端是否启动',
									icon: 'none'
								});
							}
						});
					}
				});
			},

			getBlobFromUrl(url) {
				return new Promise((resolve, reject) => {
					const xhr = new XMLHttpRequest();
					xhr.open('GET', url, true);
					xhr.responseType = 'blob';
					xhr.onload = () => {
						if (xhr.status === 200) {
							resolve(xhr.response);
						} else {
							reject(new Error('获取文件失败'));
						}
					};
					xhr.onerror = () => reject(new Error('网络错误'));
					xhr.send();
				});
			},

			getFullAvatarUrl(avatar) {
				if (!avatar) return null;
				if (avatar.startsWith('http')) return avatar;
			},

			base64ToBlob(base64Data, contentType) {
				contentType = contentType || '';
				const sliceSize = 1024;
				const byteCharacters = atob(base64Data);
				const byteArrays = [];

				for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
					const slice = byteCharacters.slice(offset, offset + sliceSize);
					const byteNumbers = new Array(slice.length);
					for (let i = 0; i < slice.length; i++) {
						byteNumbers[i] = slice.charCodeAt(i);
					}
					const byteArray = new Uint8Array(byteNumbers);
					byteArrays.push(byteArray);
				}
				return new Blob(byteArrays, {
					type: contentType
				});
			},

			editNickname() {
				this.newNickname = this.userInfo.name || '';
				this.agreePolicy = false;
				this.$nextTick(() => {
					this.$refs.nicknamePopup.open();
					this.focusInput();
				});
			},

			closeNickname() {
				this.$refs.nicknamePopup.close();
			},

			toggleAgree() {
				this.agreePolicy = !this.agreePolicy;
			},

			onPopupChange(e) {
				this.popupShow = e.show;
			},

			handleInput() {
				// 输入处理逻辑
			},

			focusInput() {
				uni.createSelectorQuery().select('.nickname-input')
					.fields({
						node: true
					}, (res) => {
						if (res.node) {
							res.node.focus();
						}
					}).exec();
			},

			async submitNickname() {
				if (!this.canSubmit) return;

				const userId = this.$store.getters['user/userId'];
				if (!userId) return;

				try {
					const updateRes = await this.$api.userApi.updateUsername({
						userId: Number(userId),
						username: this.newNickname.trim()
					});

					if (updateRes.code === 200) {
						this.userInfo.name = this.newNickname.trim();
						this.$store.commit('user/UPDATE_USER_INFO', {
							name: this.newNickname.trim()
						});
						this.closeNickname();
						uni.showToast({
							title: '昵称修改成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: updateRes.msg || '更新失败',
							icon: 'none'
						});
					}
				} catch (e) {
					console.error('修改昵称失败', e);
					uni.showToast({
						title: '修改失败: ' + (e.message || '未知错误'),
						icon: 'none'
					});
				}
			},

			async updateBalance(amount) {
				const userId = this.$store.getters['user/userId'];
				if (!userId) return;

				try {
					const res = await this.$api.userApi.updateBalance({
						id: userId,
						amount: amount
					});

					if (res.code === 200) {
						await this.loadUserInfo();
						uni.showToast({
							title: amount > 0 ? '充值成功' : '消费成功',
							icon: 'success'
						});
					}
				} catch (e) {
					uni.showToast({
						title: e.message || '操作失败',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style lang="scss">
	/* 引入公共样式 */
	@import "@/colorui/icon.css";
	@import "@/static/styles/common.scss";

	/* 间距辅助类 */
	.mb-md {
		margin-bottom: 20rpx;
	}

	/* 新增固定导航栏样式 */
	.fixed-nav-bar {
		position: fixed;
		top: -120rpx;
		left: 0;
		right: 0;
		z-index: 1000;
		background: linear-gradient(to right, #4f76a3e6, #5ec293);
		padding: 15rpx 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		transition: top 0.3s ease;

		&.show {
			top: 0;
		}

		.fixed-user-info {
			display: flex;
			align-items: center;

			.fixed-avatar {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				border: 2rpx solid #fff;
				margin-right: 20rpx;
			}

			.fixed-username {
				font-size: 32rpx;
				color: #fff;
				max-width: 300rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}

		.fixed-actions {
			display: flex;
			align-items: center;

			.fixed-action {
				display: flex;
				flex-direction: column;
				align-items: center;
				margin-left: 30rpx;
				padding: 10rpx 15rpx;
				border-radius: 10rpx;
				background-color: rgba(255, 255, 255, 0.2);

				.fixed-action-icon {
					width: 40rpx;
					height: 40rpx;
					margin-bottom: 5rpx;
				}

				.fixed-action-text {
					font-size: 24rpx;
					color: #fff;
				}
			}
		}
	}

	/* 用户信息卡片 */
	.user-card {
		position: relative;
		color: #fff;
		padding: 30rpx 20rpx 25rpx;

		.bg {
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			filter: blur(2px);
			z-index: 0;
		}

		.user-info-box {
			display: flex;
			align-items: center;
			position: relative;
			z-index: 1;

			.portrait {
				width: 160rpx;
				height: 160rpx;
				border-radius: 50%;
				border: 4rpx solid #fff;
				overflow: hidden;
				margin-right: 20rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.username {
				font-size: 36rpx;
				font-weight: 500;

				.phone {
					font-size: 24rpx;
					color: rgba(255, 255, 255, 0.8);
					margin: 10rpx 0;
				}

				.balance {
					font-size: 28rpx;
					color: #fff;
					margin-top: 10rpx;
				}

				.balance-actions {
					margin-top: 10rpx;
				}
			}
		}
	}

	/* 调整用户卡片的上边距，当导航栏固定时留出空间 */
	.page-container {
		.user-card {
			transition: margin-top 0.3s ease;
		}

		&.fixed-nav {
			.user-card {
				margin-top: 120rpx;
			}
		}
	}

	/* 网格布局 */
	.grid {
		display: flex;
		flex-wrap: wrap;

		&-3 {
			.grid-item {
				width: 33.333%;
			}
		}

		&-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20rpx 0;

			.grid-icon {
				width: 60rpx;
				height: 60rpx;
				margin-bottom: 10rpx;
			}

			.grid-text {
				font-size: 28rpx;
				color: #333;
			}
		}
	}

	/* 订单区域样式 */
	.order-section {
		display: flex;
		justify-content: space-around;
		padding: 15rpx 0;

		.order-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			width: 120rpx;

			.order-icon {
				width: 56rpx;
				height: 56rpx;
				margin-bottom: 10rpx;
			}

			text {
				font-size: 28rpx;
				color: #333;
			}
		}
	}

	/* 历史记录区域 */
	.history-section {
		padding: 0;

		.list-cell {
			padding: 20rpx;
		}
	}

	/* 弹窗样式 */
	.nickname-popup {
		background: #f8f8f8;
		border-radius: 20rpx 20rpx 0 0;
		padding: 20rpx 30rpx;
		padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
		width: 100%;
		box-sizing: border-box;
	}

	.drag-indicator {
		width: 80rpx;
		height: 8rpx;
		background-color: #ddd;
		border-radius: 4rpx;
		margin: 0 auto 20rpx;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		padding-bottom: 15rpx;
		border-bottom: 1px solid #eaeaea;
	}

	.popup-title {
		font-size: 36rpx;
		font-weight: 500;
		color: #333;
	}

	.popup-close {
		font-size: 50rpx;
		color: #999;
		line-height: 1;
		padding: 0 10rpx;
	}

	.popup-content {
		margin-bottom: 30rpx;
	}

	.nickname-input {
		height: 90rpx;
		background: #f0f0f0;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 32rpx;
		color: #333;
		width: 100%;
		box-sizing: border-box;
	}

	.input-hint {
		display: flex;
		justify-content: space-between;
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
		margin-bottom: 20rpx;

		.warning {
			color: #f56c6c;
		}
	}

	.policy-container {
		margin-top: 15rpx;
	}

	.policy-checkbox {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
		font-size: 28rpx;
		color: #666;

		.policy-label {
			margin-left: 10rpx;
		}
	}

	.policy-content {
		background-color: #f0f0f0;
		border-radius: 6rpx;
		padding: 15rpx;
		margin-top: 10rpx;
		font-size: 22rpx;
		line-height: 1.6;
		color: #666;
		max-height: 200rpx;
		overflow-y: auto;

		.policy-title {
			color: #333;
			font-weight: 500;
		}
	}

	.submit-btn--disabled {
		background-color: #999 !important;
		opacity: 0.7;
	}
</style>